<template>
  <!-- 页面-租户管理 -->
  <div class="TenantList-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form :model="formSearch" ref="roleFormSearch" slot="adaption-bar" class="ivu-form-no-margin-bottom" inline>
        <template>
          <!-- 租户编码 -->
          <Form-item prop="tenantCode" :label="$t('module.tenantManage.tenantCode')">
            <Input
              type="text"
              v-model.trim="formSearch.tenantCode"
              :placeholder="$t('module.tenantManage.placeholder.tenantCode')"
              :maxlength="30"
              @on-enter="search"
            />
          </Form-item>

          <!-- 租户名称 -->
          <Form-item prop="tenantName" :label="$t('module.tenantManage.tenantName')">
            <Input
              type="text"
              v-model.trim="formSearch.tenantName"
              :placeholder="$t('module.tenantManage.placeholder.tenantName')"
              :maxlength="30"
              @on-enter="search"
            />
          </Form-item>

          <!-- 租户类型 -->
          <Form-item prop="tenantType" :label="$t('module.tenantManage.tenantType')">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.tenantType')"
              v-model="formSearch.tenantType"
              :transfer="true"
              class="no-borderColor"
              clearable
            >
              <Option :value="1" :key="1">{{ $t("module.tenantManage.tenantTypeItem.groupCompany") }}</Option>
              <Option :value="2" :key="2">{{ $t("module.tenantManage.tenantTypeItem.company") }}</Option>
            </Select>
          </Form-item>

          <!-- 状态 -->
          <Form-item prop="enabled" :label="$t('common.status')">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.status')"
              v-model="formSearch.enabled"
              style="width: 100%;"
              clearable
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <!-- 分配应用 -->
          <Form-item prop="applicationCode" :label="$t('module.tenantManage.allotApp')">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.assignApp')"
              v-model="formSearch.applicationCode"
              style="width: 100%;"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in searchAllotAppList"
                :value="item.vsiKey"
                :key="item.vsiKey"
                :style="{ color: item.enabled == 0 ? '#bcbcbc' : '' }"
                :label="item.vsiValue"
              ></Option>
            </Select>
          </Form-item>
          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="formReset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="tenantTable" :config="tableConfig" @page-change="pageChange">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="formReset" />
      </div>
      -->
      <div slot="table-bar">
        <RPButton optType="create" @click="edit()" />
      </div>
      <Form :model="formSearch" 
        slot="table-search-bar"
        v-if="useTableSearchBar"
        ref="roleFormSearch"
        class="ivu-form-no-margin-bottom" inline>
      <template>
          <!-- 租户类型 -->
          <Form-item prop="tenantType">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.tenantType')"
              v-model="formSearch.tenantType"
              :transfer="true"
              style="width: 140px"
              class="no-borderColor"
              @on-change="search(1)"
              clearable
            >
              <Option :value="1" :key="1">{{ $t("module.tenantManage.tenantTypeItem.groupCompany") }}</Option>
              <Option :value="2" :key="2">{{ $t("module.tenantManage.tenantTypeItem.company") }}</Option>
            </Select>
          </Form-item>

          <!-- 状态 -->
          <Form-item prop="enabled">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.status')"
              v-model="formSearch.enabled"
              @on-change="search(1)"
              style="width: 140px"
              clearable
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <!-- 分配应用 -->
          <Form-item prop="applicationCode">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.assignApp')"
              v-model="formSearch.applicationCode"
              @on-change="search(1)"
              style="width: 240px"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in searchAllotAppList"
                :value="item.vsiKey"
                :key="item.vsiKey"
                :style="{ color: item.enabled == 0 ? '#bcbcbc' : '' }"
                :label="item.vsiValue"
              ></Option>
            </Select>
          </Form-item>
          <Form-item prop="searchType">
            <Input
              type="text"
              v-model.trim="formSearch.searchTypeValue"
              :placeholder="searchTypePlaceholder"
              @on-enter="search"
              @on-blur="search"
            >
            <template #prepend>
              <Select v-model="formSearch.searchType" style="width: 110px" @on-change="searchTypeChange">
                <Option v-for="item in searchTypeList" :value="item.key" :key="item.key">{{
                item.name
              }}</Option>
              </Select>
            </template>
            </Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import locales from "./locales.js";
import { generateColumns } from "./columns.js";
import { getTenantList, getUserCenterList, delTenant, getApplicationByTenantCode } from "@/api/teantManageAPI.js";
import TenantEdit from "./TenantEdit.vue";
import { CoreModuleName } from "@/const";
import TenantConfig from "./TenantConfig.vue";
import TenantAdmin from "./TenantAdmin.vue";
import AuthorizeDevelop from "./AuthorizeDevelop.vue";
// import valueSetAPI from "@/api/valueSetAPI.js";
// import { getLowcodeDataSyncEnable } from "@/api/orgApi";

export default {
  name: "tenant-list",
  mixins: [locales],
  data() {
    return {
      useTableSearchBar: false,
      userRepositorys: {},
      formSearch: {
        tenantCode: "",
        tenantName: "",
        tenantType: null,
        enabled: "ALL", //状态
        applicationCode: "ALL", //分配应用
        searchType: 'tenantCode',
        searchTypeValue: '',
      },
      searchStatusList: [], // 状态选择器列表
      searchAllotAppList: [], // 分配应用选择器列表
      searchTypeList: [
        {key: 'tenantCode',  name: this.$t('module.tenantManage.tenantCode'), placeholder: this.$t('module.tenantManage.placeholder.tenantCode')},
        {key: 'tenantName',  name: this.$t('module.tenantManage.tenantName'), placeholder: this.$t('module.tenantManage.placeholder.tenantName')},
      ],
      searchTypePlaceholder: this.$t('module.tenantManage.placeholder.tenantCode'),
    }
  },
  computed: {
    tableConfig() {
      return { loadDataFn: getTenantList, columnsFn: generateColumns.bind(this) };
    }
  },
  created() {
    //   获取用户中心列表
    getUserCenterList()
      .then(res => {
        const item = {};
        res.data.forEach(val => {
          item[val.userCenterId] = val.userCenterName;
        });
        this.userRepositorys = item;
        this.search();
      })
      .catch(err => {
        this.$message.error({
          content: err.message,
          duration: 3
        });
      });
    this.searchStatusList = [
      {
        vsiKey: "0",
        vsiValue: this.$t("common.disable")
      },
      {
        vsiKey: "1",
        vsiValue: this.$t("common.enable")
      }
      // {
      //   vsiKey: "ALL",
      //   vsiValue: this.$t("common.whole")
      // }
    ];
    // this.getStatusList();
    this.getApplicationByTenantCode();
    // getLowcodeDataSyncEnable().then(res => {
    //   this.showdeveloper = res.data
    // })
  },
   watch: {
    'formSearch.searchType' : {
      handler() {
        let selectItem = this.searchTypeList.find(item => item.key == this.formSearch.searchType)
        this.searchTypePlaceholder =  selectItem ? selectItem.placeholder : ''
      }
    }
  },
  // deactivated(){
  //   // this.$destroy();
  // },
  methods: {
    pageChange (page) {
      console.log('page', page)
    },
    searchTypeChange() {
      if (this.formSearch.searchTypeValue) {
        this.search()
      }
    },
    assginTenantAdmin(row) {
      new this.$pageModal(
        TenantAdmin,
        {
          props: {
            tenantInfo: row
          }
        },
        data => {}
      );
    },
    goRole(row) {
      new this.$pageModal(
        AuthorizeDevelop,
        {
          props: {
            tenantInfo: row
          }
        },
        data => {}
      );
    },
    // 配置租户
    configTenant(row) {
      new this.$pageModal(
        TenantConfig,
        {
          props: {
            tenantInfo: row
          }
        },
        data => {
          if (data) {
            this.search();
          }
        }
      );
    },
    // 获取状态选择器列表
    // getStatusList() {
    //   valueSetAPI.getValueSetByCode("ENABLED_CODE").then(res => {
    //     this.searchStatusList = res;
    //   });
    // },
    // 获取分配应用选择器列表：数字化所有应用的应用编码
    getApplicationByTenantCode() {
      getApplicationByTenantCode(window.RPConfig.rootTenantCode).then(res => {
        this.searchAllotAppList = res.data.map(item => {
          return {
            vsiKey: item.clientId,
            vsiValue: item.appName,
            enabled: item.enabled
          };
        });
      });
    },
    // 获取用户名
    getUserCenterName(id) {
      return this.userRepositorys[id] || id;
    },
    getIndex(index) {
      let num = this.$refs.tenantTable.currentPage < 1 ? 1 : this.$refs.tenantTable.currentPage;
      return (num - 1) * this.$refs.tenantTable.param.pageSize + index + 1;
    },
    search(page = 1) {
      // this.$refs["tenantTable"].load(Object.assign({}, this.formSearch), page);
      let searchParams = Object.assign({}, this.formSearch);
      if(this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.formSearch.searchType == item.key) {
            searchParams[item.key] = this.formSearch.searchTypeValue
          } else {
            searchParams[item.key] = ''
          }
        })
      }
      delete searchParams.searchType
      delete searchParams.searchTypeValue
      if (searchParams.enabled == "ALL") {
        searchParams.enabled = null;
      }
      if (searchParams.applicationCode == "ALL") {
        searchParams.applicationCode = null;
      }
      this.$refs["tenantTable"].load(searchParams, page);
    },
    edit(row) {
      new this.$pageModal(
        TenantEdit,
        {
          props: {
            tenantInfo: {
              id: row && row.id,
              tenantCode: row && row.tenantCode
            },
            rowList: row ? row : {},
            userRepositorys: this.userRepositorys
          }
        },
        data => {
          if (data) {
            this.search(this.$refs.tenantTable.param.pageNum);
            this.$store.commit(CoreModuleName + "/clearAllCache");
          }
        }
      );
    },
    // deleted(id) {
    //   new $confirm(this.$t("module.flexField.warning.confirmToDelete"), this).then(() => {
    //     delTenant(id).then(res => {
    //       this.$message.error({
    //         content: "删除成功",
    //         duration: 3
    //       });
    //       this.search();
    //     });
    //   });
    // },
    formReset() {
      this.$refs["roleFormSearch"].resetFields();
      this.search();
    },
  }
};
</script>

<style lang="less">
// ok注释的样式
.TenantList-page {
  .ivu-form-item {
    .ivu-form-item-label {
      line-height: 14px !important;
    }
  }
}
</style>
